package com.rederxu.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import com.rederxu.tools.BitmapUtil;
import com.rederxu.tools.StorageUtils;

/**
 * 异步加载图片，应该在UI线程中调用
 * 示例代码如下：
 * 
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;String url = input.getText().toString();
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;ImageTask task = new ImageTask(img,"/mnt/sdcard/",new ImageTaskListener() {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;	
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onTaskOver(ImageView img) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		// TODO Auto-generated method stub
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("loadImg", "图片下载完成");
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;	
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onDownloading(int max, int progress) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("loadImg", "图片下载进度：" + progress + "/" + max);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;});
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;ImageTaskOpion option = task.getImageTaskOpion();
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;option.setAutoVisibility(radio1.isChecked());
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;option.setOverlap(radio2.isChecked());
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;option.setAutoCompress(radio3.isChecked());
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;task.setOption(option);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;task.execute(url);
 * */
public class ImageTask extends AsyncTask<String,Integer,Bitmap>{

	private ImageView img = null;
	private ImageTaskListener listener = null;
	private int fileMax = 0;
	private String path = null;
	private ImageTaskOpion option = new ImageTaskOpion();
	
	public ImageTask(ImageView imageView,String path,ImageTaskListener listener){
		this.img = imageView;
		this.listener = listener;
		this.path = path;
		if(path == null){
			this.path = StorageUtils.getSdCardPath();
		}
	}
	
	public void setOption(ImageTaskOpion option){
		if(option != null){
			this.option = option;
		}
	}
	
	@Override
	protected Bitmap doInBackground(String... urls) {
		try{
			File f = new File(urls[0]);
			String filePath = path + f.getName();
			Log.d("filePath", filePath);
			File file = new File(filePath);
			if(!file.exists()){
				file.createNewFile();
			}else{
				if(!option.isOverlap){
					return BitmapFactory.decodeFile(filePath);
				}
			}
			URL url = new URL(urls[0]);
			URLConnection con = url.openConnection();
			InputStream is = con.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			fileMax = con.getContentLength();
			int progress = 0;
			OutputStream os = new FileOutputStream(filePath);
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
				progress += len;
				publishProgress(progress);
			}
			os.close();
			is.close();
			if(option.isAutoCompress){
				while(file.length() > option.getByteLimite() + 50 *1024){
					BitmapFactory.Options options = new Options();
					options.inPreferredConfig=Bitmap.Config.ARGB_4444;
					options.inJustDecodeBounds = false;
					options.inSampleSize = BitmapUtil.calculateInSampleSize(file.length(),option.getByteLimite());
					options.inPurgeable = true; 
					options.inInputShareable = true; 
					Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
					BitmapUtil.saveBitmap(bitmap, file);
					bitmap.recycle();
					file = new File(filePath);
				}
			}
			Bitmap bitmap = BitmapFactory.decodeFile(filePath);
			return bitmap;
		}catch(Exception e){
			e.printStackTrace();
			Log.e("fileDownload", e.toString());
		}
		return null;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		img.setImageBitmap(result);
		if(listener != null)
			listener.onTaskOver(img);
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) {
		if(listener != null)
			listener.onDownloading(fileMax, values[0]);
		super.onProgressUpdate(values);
	}
	
	public ImageTaskOpion getImageTaskOpion(){
		return option;
	}
	
	public class ImageTaskOpion{
		//图片存在时是否覆盖,不覆盖可以节省流量
		private boolean isOverlap = false;
		//图片下载失败自动隐藏
		private boolean isAutoVisibility = true;
		//是否自动压缩
		private boolean isAutoCompress = true;
		//期待压缩后图片文件大小，默认50k
		private long byteLimite = 50 * 1024;
		/**
		 * 图片下载失败自动隐藏
		 * */
		public boolean isAutoVisibility() {
			return isAutoVisibility;
		}
		/**
		 * 图片下载失败自动隐藏
		 * */
		public void setAutoVisibility(boolean isAutoVisibility) {
			this.isAutoVisibility = isAutoVisibility;
		}
		/**
		 * 是否自动压缩
		 * */
		public boolean isAutoCompress() {
			return isAutoCompress;
		}
		/**
		 * 是否自动压缩
		 * */
		public void setAutoCompress(boolean isAutoCompress) {
			this.isAutoCompress = isAutoCompress;
		}
		/**
		 * 图片存在时是否覆盖,不覆盖可以节省流量
		 * */
		public boolean isOverlap() {
			return isOverlap;
		}
		/**
		 * 图片存在时是否覆盖,不覆盖可以节省流量
		 * */
		public void setOverlap(boolean isOverlap) {
			this.isOverlap = isOverlap;
		}
		/**
		 * 期待压缩后图片文件大小，默认50k，由于压缩比例是一个int类型，所以压缩结果可能在(30kb,byteLimite + 50kb)以内
		 * */
		public long getByteLimite() {
			return byteLimite;
		}
		/**
		 * 必须：
		 * <h1>byteLimite >= 50 * 1024 (小于会变成50 * 1024)</h1>
		 * 期待压缩后图片文件大小，默认50k，由于压缩比例是一个int类型，所以压缩结果可能在(30kb,byteLimite + 50kb)以内
		 * */
		public void setByteLimite(long byteLimite) {
			if(byteLimite < 50 * 1024){
				byteLimite = 50 * 1024;
			}
			this.byteLimite = byteLimite;
		}
	}
}
